package org.yray.javacpp.audio;

import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class G711Grabber {

    public static byte[] wav2G711(byte[] bs)
    {
        ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bs);
        FFmpegFrameGrabber grabber=new FFmpegFrameGrabber(byteArrayInputStream);
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        try {
            grabber.start();
            FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputStream, 1);
            // 码率恒定
            recorder.setAudioOption("crf","0");
            recorder.setAudioCodec(avcodec.AV_CODEC_ID_PCM_ALAW);
            recorder.setAudioBitrate(16);
            recorder.setAudioChannels(1);
            recorder.setSampleRate(8000);
            recorder.setAudioQuality(0);
            recorder.setAudioOption("aq","10");
            recorder.start();
            Frame audioFrame = null;
            while ((audioFrame = grabber.grab()) != null) {
                recorder.setTimestamp(grabber.getTimestamp());
                recorder.record(audioFrame);
            }
            grabber.flush();
            grabber.stop();
            recorder.stop();
            recorder.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }
}
